package com.zmj.leetcode;

/**
 * 二数之和
 *
 * @author zmj
 */


import java.util.HashMap;

/**
 * j = i + 1 ,因为 例如数组是 {3,3}，target是6 ,如果不跳过自己，会重复
 */
public class Code01TwoSum {

    public static void main(String[] args) {

        int[] mus = {3, 3};
        int target = 6;
        int[] ints = twoSumHash(mus, target);
        for (int num : ints) {
            System.out.println("num = " + num);
        }
    }


    /**
     * 暴力的双层for
     *
     * @param nums
     * @param target
     * @return
     */
    public static int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            int findNum = target - nums[i];
            for (int j = i + 1; j < nums.length; j++) {
                if (findNum == nums[j]) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[]{};
    }

    /**
     * hash算法
     *
     * @param nums
     * @param target
     * @return
     */
    public static int[] twoSumHash(int[] nums, int target) {

        HashMap<Integer, Integer> findMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int findNum = target - nums[i];
            if (findMap.containsKey(findNum)) {
                return new int[]{i, findMap.get(findNum)};
            }
            findMap.put(nums[i], i);
        }
        return new int[]{};
    }
}
